package com.dkd.day20250615;

import com.dkd.day20250614.ListNode;

public class SolutionFindKthToTail {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);

        ListNode head2 = FindKthToTail2(head, 4);

        while (head2 != null) {
            System.out.println(head2.val);
            head2 = head2.next;
        }
    }
    public static ListNode FindKthToTail (ListNode pHead, int k) {
        // write code here
        //伪码实现
        //用list集合存储链表
        //计算链表长度
        //得到list对应位置
        //返回该位置节点
        //优化，计算链表长度，然后返回length-k
        return null;
    }

    public static ListNode FindKthToTail2 (ListNode pHead, int k) {
        // write code here
        //双指针
        //1判断非空
        if (pHead == null) return null;
        //2双指针，第一个指针移动k,然后第二个指针和第一个指针一起移动，直到没有,p2就是倒数k
        ListNode slow = pHead;
        ListNode fast = pHead;
        while(fast!=null && k>0){
            fast = fast.next;
            k--;
        }
        System.out.println(k);
        if (fast==null && k>0) return null;
        while (fast!=null ){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}
